import { defineStore } from 'pinia'
import { TypeUser } from '@src/interfaces/TypeUser.ts'
import { onMounted, ref } from 'vue'
import TokenUtil from '@util/TokenUtil.ts'
import { router } from '@util/RouterUtil.ts'
import { ElMessage } from 'element-plus'

const useUserStore = defineStore('userStore', () => {
  const userInfo = ref<TypeUser>({
    role: '普通用户',
    password: '',
    account: '',
    classId: 0,
    id: 0,
    name: '?',
    phone: '',
    status: '正常',
  })
  TokenUtil.onSetToken(() => {
    getUserInfoFormToken()
  })

  /**
   * 从token中解析出用户信息
   */
  const getUserInfoFormToken = () => {
    const token = TokenUtil.getToken()
    if (!token) {
      TokenUtil.removeToken()
      toLogin()
      return
    }
    userInfo.value = TokenUtil.parseJwt(token)
  }

  /**
   * 跳转到用户登录页
   */
  const toLogin = () => {
    return router.push('/login')
  }

  /**
   * 退出登录
   */
  const logout = () => {
    TokenUtil.removeToken()
    ElMessage.success('退出成功')
    return toLogin()
  }

  onMounted(() => {
    getUserInfoFormToken()
  })

  return {
    userInfo,
    toLogin,
    logout,
  }
})

export default useUserStore
